package com.tccdemo;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class AmountOp
{
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public Account findById()
    {
        return jdbcTemplate.queryForObject("select * from account where id=1", new AccountMapper());
    }

    @Transactional
    public void deac()
    {
        jdbcTemplate.update("update account set amount =amount-10 ,froze =froze+10 where id=1");
    }

    @Transactional
    public void add()
    {
        jdbcTemplate.update("update account set amount = amount+10,froze=froze-10 where id=1");
    }

    @Transactional
    public void confirm()
    {
        jdbcTemplate.update("update account set froze=froze-10 where id=1");
    }

    static class AccountMapper implements RowMapper<Account>
    {

        @Override
        public Account mapRow(ResultSet resultSet, int i) throws SQLException
        {
            int     id      = resultSet.getInt("id");
            int     amount  = resultSet.getInt("amount");
            Account account = new Account();
            account.setAmount(amount);
            account.setId(id);
            return account;
        }
    }
}
